// GTA RWTEX file loader example by The_GTA.
// Contains useful utilities if you want to load RenderWare textures natively.
// Uses DK22Pac's plugin sdk.

#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>

#include <plugin.h>
#include <game_sa/CSprite2d.h>
#include <game_sa/RenderWare.h>

using namespace plugin;

static CSprite2d *drawTexSprite = NULL;

template <typename retType, typename... Args>
struct sa_func_def
{
    typedef retType (__cdecl*function_t)( Args... );

    inline sa_func_def( DWORD ptr )
    {
        this->func_ptr = (void*)ptr;
    }

    inline retType operator () ( Args... args ) const
    {
        return ( (function_t)this->func_ptr )( args... );
    }

private:
    void *func_ptr;
};

static const sa_func_def <RwTexture*, RwStream*> RwTextureStreamReadRockstar( 0x00730E60 );

static RwTexture* loadRWTEXFromDisc( const char *path )
{
    RwTexture *texHandle = NULL;

    RwStream *imgStream = RwStreamOpen( rwSTREAMFILENAME, rwSTREAMREAD, (void*)path );

    if ( imgStream )
    {
        texHandle = RwTextureStreamReadRockstar( imgStream );

        RwStreamClose( imgStream, NULL );
    }

    return texHandle;
}

class RWTEXRenderExample
{
public:
    inline RWTEXRenderExample()
    {
        Events::drawingEvent += [] {
            if ( drawTexSprite )
            {
                drawTexSprite->Draw(CRect(10.0f, 10.0f, 300.0f, 300.0f), CRGBA(255, 255, 255, 255));
            }
        };

        Events::initRwEvent += [] {
            if ( drawTexSprite )
                return;

            drawTexSprite = new CSprite2d();

            if ( drawTexSprite )
            {
                drawTexSprite->m_pTexture = loadRWTEXFromDisc( "test.rwtex" );
            }
        };

        Events::shutdownRwEvent += [] {
            if ( drawTexSprite )
            {
                delete drawTexSprite;
                drawTexSprite = NULL;
            }
        };
    }
} render_plg;